package interfaces

import (
	"deploy/interfaces/db"
	"deploy/schema"
	"deploy/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
)

func (s *Server)AgentList(c *gin.Context){
	data := schema.SchemaAgentList{}
	result := schema.Result{Data: &data}
	defer func() {
		if err := recover(); err != nil {
			if result.Code==0{
				result.Code = 400
			}
			result.Err = fmt.Sprintf("%s",err)
		}
		data.Count= len(data.AgentList)
		c.JSON(result.Code,result)
	}()

	// 1、参数校验

	// 2、查数据
	s.mapLock.Lock()
	for _,client := range s.OnlineClientMap{
		groups:=[]string{}
		err := s.Db.GetServerNameByInstanceName(client.Name,&groups)
		if err !=nil {
			log.Println(err.Error())
		}
		instance := map[string]interface{}{"instance":client.Name,"server":groups,"ip":client.Ip}
		data.AgentList = append(data.AgentList, instance)
	}
	s.mapLock.Unlock()
	// 3、构建返回数据
	result.Code=200
	result.Msg="查询在线服务器列表成功"
}

func (s *Server)GetAgentFromDb(c *gin.Context){
	data := schema.SchemaAgentList{}
	result := schema.Result{Data: &data}
	defer func() {
		if err := recover(); err != nil {
			if result.Code==0{
				result.Code = 400
			}
			result.Err = fmt.Sprintf("%s",err)
		}
		data.Count= len(data.AgentList)
		c.JSON(result.Code,result)
	}()

	// 1、参数校验

	// 2、查数据

	instances:=[]db.Instance{}
	err := s.Db.GetAllInstance(&instances)
	if err!=nil{
		result.Code=500
		result.Msg="查询服务器列表失败"
		return
	}
	// 3、构建返回数据
	for _,instance := range instances{
		groups:=[]string{}
		err = s.Db.GetServerNameByInstanceName(instance.HostName,&groups)
		if err !=nil{
			groups = []string{"N/A"}
		}
		row := map[string]interface{}{"instance":instance.HostName,"server":groups,"ip":instance.Ip,"is_online":instance.IsOnline}
		data.AgentList = append(data.AgentList, row)
	}
	result.Code=200
	result.Msg="查询在线服务器列表成功"
}



func (s *Server)GetAllServerName(c *gin.Context) {
	data := schema.SchemaAgentList{}
	result := schema.Result{Data: &data}
	defer func() {
		if err := recover(); err != nil {
			if result.Code == 0 {
				result.Code = 400
			}
			result.Err = fmt.Sprintf("%s", err)
		}
		data.Count = len(data.AgentList)
		c.JSON(result.Code, result)
	}()
	serverName := utils.GetServerNameSlice()
	result.Code=200
	result.Msg="获取服务名成功"
	result.Data=serverName
}
